package com.dji.controller;

import com.dji.dao.DroneDao;
import com.dji.dao.MissionDao;
import com.dji.model.Drone;
import com.dji.model.Mission;
import com.dji.model.Waypoint;
import org.json.JSONArray;
import org.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * 处理无人机飞行任务规划相关的请求
 */
public class MissionPlanningServlet extends HttpServlet {
    private MissionDao missionDao = new MissionDao();
    private DroneDao droneDao = new DroneDao();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String droneId = request.getParameter("droneId");
        String missionId = request.getParameter("missionId");
        
        if (missionId != null) {
            // 获取单个任务详情
            Mission mission = missionDao.getMissionById(missionId);
            if (mission != null) {
                JSONObject jsonMission = convertMissionToJson(mission);
                sendJsonResponse(response, jsonMission);
            } else {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "任务未找到");
            }
        } else if (droneId != null) {
            // 获取指定无人机的所有任务
            List<Mission> missions = missionDao.getMissionsByDroneId(droneId);
            JSONArray jsonArray = new JSONArray();
            
            for (Mission mission : missions) {
                jsonArray.put(convertMissionToJson(mission));
            }
            
            sendJsonResponse(response, jsonArray);
        } else {
            // 获取所有任务
            List<Mission> missions = missionDao.getAllMissions();
            JSONArray jsonArray = new JSONArray();
            
            for (Mission mission : missions) {
                jsonArray.put(convertMissionToJson(mission));
            }
            
            sendJsonResponse(response, jsonArray);
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // 读取请求体中的JSON数据
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = request.getReader();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        
        try {
            JSONObject jsonRequest = new JSONObject(sb.toString());
            String action = jsonRequest.optString("action", "");
            
            if ("create".equals(action)) {
                // 创建新任务
                String name = jsonRequest.getString("name");
                String droneId = jsonRequest.getString("droneId");
                
                // 验证无人机是否存在
                Drone drone = droneDao.getDroneById(droneId);
                if (drone == null) {
                    sendErrorResponse(response, HttpServletResponse.SC_BAD_REQUEST, "无人机不存在");
                    return;
                }
                
                Mission mission = new Mission(name, droneId);
                
                // 添加航点
                if (jsonRequest.has("waypoints")) {
                    JSONArray waypointsArray = jsonRequest.getJSONArray("waypoints");
                    for (int i = 0; i < waypointsArray.length(); i++) {
                        JSONObject waypointJson = waypointsArray.getJSONObject(i);
                        Waypoint waypoint = new Waypoint(
                            waypointJson.getDouble("latitude"),
                            waypointJson.getDouble("longitude"),
                            waypointJson.getDouble("altitude"),
                            i + 1
                        );
                        
                        if (waypointJson.has("action")) {
                            waypoint.setAction(waypointJson.getString("action"));
                        }
                        
                        if (waypointJson.has("hoverTime")) {
                            waypoint.setHoverTime(waypointJson.getInt("hoverTime"));
                        }
                        
                        mission.addWaypoint(waypoint);
                    }
                }
                
                missionDao.saveMission(mission);
                
                // 返回创建的任务
                JSONObject jsonResponse = convertMissionToJson(mission);
                jsonResponse.put("message", "任务创建成功");
                sendJsonResponse(response, jsonResponse);
            } else if ("execute".equals(action)) {
                // 执行任务
                String missionId = jsonRequest.getString("missionId");
                Mission mission = missionDao.getMissionById(missionId);
                
                if (mission == null) {
                    sendErrorResponse(response, HttpServletResponse.SC_NOT_FOUND, "任务未找到");
                    return;
                }
                
                // 更新任务状态为执行中
                mission.setStatus("EXECUTING");
                missionDao.saveMission(mission);
                
                // 更新无人机状态
                Drone drone = droneDao.getDroneById(mission.getDroneId());
                if (drone != null) {
                    drone.setStatus("FLYING");
                    droneDao.saveDrone(drone);
                }
                
                // 返回响应
                JSONObject jsonResponse = new JSONObject();
                jsonResponse.put("success", true);
                jsonResponse.put("message", "任务开始执行");
                jsonResponse.put("missionId", mission.getId());
                jsonResponse.put("status", mission.getStatus());
                sendJsonResponse(response, jsonResponse);
            } else {
                sendErrorResponse(response, HttpServletResponse.SC_BAD_REQUEST, "未知的操作类型");
            }
        } catch (Exception e) {
            sendErrorResponse(response, HttpServletResponse.SC_BAD_REQUEST, "请求格式错误: " + e.getMessage());
        }
    }
    
    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String missionId = request.getParameter("missionId");
        
        if (missionId != null) {
            Mission mission = missionDao.getMissionById(missionId);
            
            if (mission != null) {
                missionDao.deleteMission(missionId);
                
                JSONObject jsonResponse = new JSONObject();
                jsonResponse.put("success", true);
                jsonResponse.put("message", "任务已删除");
                sendJsonResponse(response, jsonResponse);
            } else {
                sendErrorResponse(response, HttpServletResponse.SC_NOT_FOUND, "任务未找到");
            }
        } else {
            sendErrorResponse(response, HttpServletResponse.SC_BAD_REQUEST, "缺少missionId参数");
        }
    }
    
    /**
     * 将Mission对象转换为JSON对象
     */
    private JSONObject convertMissionToJson(Mission mission) {
        JSONObject jsonMission = new JSONObject();
        jsonMission.put("id", mission.getId());
        jsonMission.put("name", mission.getName());
        jsonMission.put("droneId", mission.getDroneId());
        jsonMission.put("status", mission.getStatus());
        jsonMission.put("createdTime", mission.getCreatedTime());
        
        JSONArray waypointsArray = new JSONArray();
        for (Waypoint waypoint : mission.getWaypoints()) {
            JSONObject jsonWaypoint = new JSONObject();
            jsonWaypoint.put("id", waypoint.getId());
            jsonWaypoint.put("latitude", waypoint.getLatitude());
            jsonWaypoint.put("longitude", waypoint.getLongitude());
            jsonWaypoint.put("altitude", waypoint.getAltitude());
            jsonWaypoint.put("order", waypoint.getOrder());
            jsonWaypoint.put("action", waypoint.getAction());
            jsonWaypoint.put("hoverTime", waypoint.getHoverTime());
            
            waypointsArray.put(jsonWaypoint);
        }
        
        jsonMission.put("waypoints", waypointsArray);
        return jsonMission;
    }
    
    /**
     * 发送JSON响应
     */
    private void sendJsonResponse(HttpServletResponse response, Object jsonData) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        out.print(jsonData.toString());
        out.flush();
    }
    
    /**
     * 发送错误响应
     */
    private void sendErrorResponse(HttpServletResponse response, int statusCode, String message) throws IOException {
        response.setStatus(statusCode);
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        
        JSONObject jsonError = new JSONObject();
        jsonError.put("success", false);
        jsonError.put("message", message);
        
        PrintWriter out = response.getWriter();
        out.print(jsonError.toString());
        out.flush();
    }
}